<template>
    <div class="flex gap-4 h-full">
      <!-- 历史记录侧边栏 -->
      <div class="w-[240px] bg-white rounded-lg shadow-lg overflow-hidden flex flex-col">
        <div class="bg-gradient-to-r from-blue-400 to-blue-600 px-4 py-3">
          <div class="flex items-center text-white">
            <i class="fas fa-history mr-2 text-lg"></i>
            <span class="text-lg font-semibold">历史记录</span>
          </div>
        </div>
        
        <!-- 历史记录列表 -->
        <div class="flex-1 p-3 overflow-y-auto custom-scrollbar">
          <div v-for="(record, index) in historyRecords" :key="index"
              class="border-b border-gray-100 pb-3 mb-3 hover:bg-blue-50 rounded-lg p-2 transition-colors cursor-pointer"
              :class="{'bg-blue-50': selectedSessionId === record[0].sessionId}"
              @click="openHistoryDialog(record)">
            
            <div class="flex justify-between items-start">
              <div class="flex-1 min-w-0">
                <div class="text-sm font-medium text-gray-800 mb-1 truncate">{{ record[0].question }}</div>
                <div class="text-xs text-gray-500 flex items-center">
                  <i class="far fa-clock mr-1"></i>
                  {{ formatDate(record[0].createTime) }}
                </div>
              </div>
              
              <el-popconfirm
                  width="220"
                  :icon="InfoFilled"
                  icon-color="#626AEF"
                  title="您确定删除此会话记录吗？"
                  @confirm="handleDelete(record[0].sessionId)"
                  @cancel="onCancel">
                
                <template #reference>
                  <button 
                      class="text-gray-400 hover:text-red-500 p-1 transition-colors"
                      @click.stop>
                    <i class="iconfont icon-shanchu text-sm"></i>
                  </button>
                </template>
              </el-popconfirm>
            </div>
          </div>
        </div>
        
        <!-- 新建对话按钮 -->
        <div class="p-3 border-t border-gray-100">
          <button
              @click="createNewConversation"
              class="w-full bg-gradient-to-r from-blue-500 to-blue-600 hover:from-blue-600 hover:to-blue-700 text-white py-2 px-4 rounded-lg transition-all flex items-center justify-center shadow-md hover:shadow-lg">
            <i class="fas fa-plus mr-2"></i>
            新建对话
          </button>
        </div>
      </div>
  
      <!-- AI问答区域 -->
      <div class="flex-1 bg-white rounded-lg shadow-lg overflow-hidden flex flex-col max-w-3xl">
        <div class="bg-gradient-to-r from-blue-400 to-blue-600 px-4 py-3 flex justify-between items-center">
          <div class="flex items-center text-white">
            <i class="iconfont icon-jiqiren_o text-2xl mr-2"></i>
            <span class="text-lg font-semibold">AI 智能助手</span>
          </div>
          <button 
              class="text-white hover:bg-white/20 p-1 rounded-full transition-colors"
              @click="closeAIChat"
              title="关闭聊天">
            <i class="fas fa-times text-lg"></i>
          </button>
        </div>
        
        <!-- 聊天内容区域 -->
        <div class="flex-1 p-4 overflow-y-auto custom-scrollbar bg-gray-50">
          <!-- 欢迎消息 -->
          <div v-if="selectedSessionId === null" class="flex items-start mb-6 animate-fade-in">
            <div class="w-9 h-9 rounded-full bg-gradient-to-r from-blue-400 to-blue-600 flex-shrink-0 flex items-center justify-center text-white mr-3 shadow-md">
              <i class="iconfont icon-jiqiren_o text-xl"></i>
            </div>
  
            <div class="bg-white rounded-xl p-4 max-w-[85%] shadow-sm border border-gray-100">
              <p class="text-gray-800 leading-relaxed">您好！我是AI智能助手，可以为您解答各种问题。请问有什么可以帮您的吗？</p>
            </div>
          </div>
          
          <!-- 聊天消息 -->
          <div v-for="(message, index) in chatMessages" :key="index" class="flex flex-col gap-4 mb-6 last:mb-0">
            <!-- 用户问题 -->
            <div class="flex justify-end animate-fade-in">
              <div class="bg-gradient-to-r from-blue-500 to-blue-600 text-white rounded-xl p-4 max-w-[85%] shadow-md">
                <p class="leading-relaxed">{{ message.question }}</p>
              </div>
            </div>
  
            <!-- AI回答 -->
            <div class="flex items-start animate-fade-in">
              <div class="w-9 h-9 rounded-full bg-gradient-to-r from-blue-400 to-blue-600 flex-shrink-0 flex items-center justify-center text-white mr-3 shadow-md">
                <i class="iconfont icon-jiqiren_o text-xl"></i>
              </div>
  
              <div class="bg-white rounded-xl p-4 max-w-[85%] shadow-sm border border-gray-100">
                <p class="text-gray-800 leading-relaxed whitespace-pre-wrap">{{ message.answer }}</p>
              </div>
            </div>
          </div>
        </div>
        
        <!-- 输入区域 -->
        <div class="border-t border-gray-200 p-4 bg-white">
          <div class="flex items-end gap-3">
            <div class="flex-1 relative">
              <textarea
                  v-model="userInput"
                  @keydown.enter.exact.prevent="sendMessage"
                  class="w-full ml-2 px-6 py-3 pr-12 rounded-xl border-2 border-gray-200 focus:border-blue-500 focus:ring-0 resize-none transition-all"
                  style="height: 56px; min-height: 56px;"
                  placeholder="输入您的问题（消耗1积分）"
                  :disabled="isSending"></textarea>
              
              <div class="absolute right-3 bottom-3 flex items-center gap-2">
                <span class="text-xs text-gray-500">{{ userInput.length }}/500</span>
                <button 
                    @click="clearInput"
                    class="text-gray-400 hover:text-gray-600 transition-colors"
                    title="清空输入">
                  <i class="fas fa-times-circle"></i>
                </button>
              </div>
            </div>
            
            <button 
                @click="sendMessage"
                :disabled="!userInput.trim() || isSending"
                class="ml-2 px-6 py-3 text-lg rounded-xl bg-gradient-to-r from-blue-500 to-blue-600 text-white hover:from-blue-600 hover:to-blue-700 whitespace-nowrap transition-all shadow-md hover:shadow-lg disabled:opacity-50 disabled:cursor-not-allowed"
                style="height: 56px;">
              <i class="fas fa-paper-plane mr-2"></i>
              发送
            </button>
          </div>
          
          <div class="mt-2 text-xs text-gray-500 flex items-center justify-end">
            <i class="fas fa-info-circle mr-1"></i>
            每次问答消耗1积分，请确保账户有足够积分
          </div>
        </div>
      </div>
      
      <!-- 历史记录弹框 -->
      <el-dialog 
          v-model="showHistoryDialog" 
          width="70%" 
          top="5vh"
          class="ai-chat-dialog"
          :modal="true"
          :close-on-click-modal="false">
        
        <div class="relative">
          <button 
              class="absolute top-0 right-0 text-gray-500 hover:text-gray-700 p-2 transition-colors"
              @click="showHistoryDialog = false">
            <i class="fas fa-times text-xl"></i>
          </button>
  
          <h3 class="text-2xl font-bold mb-6 text-gray-800 border-b pb-3 flex items-center">
            <i class="iconfont icon-jiqiren_o text-blue-500 mr-2"></i>
            历史对话详情
          </h3>
  
          <div class="ai-chat-content max-h-[70vh] overflow-y-auto custom-scrollbar">
            <history-dialog :date="selectedDate" v-model="showHistoryDialog" />
          </div>
        </div>
      </el-dialog>
    </div>
  </template>
  
  <script setup>
  import { ref, onMounted } from 'vue'
  import historyDialog from './historyDialog.vue';
  import { InfoFilled } from '@element-plus/icons-vue'
  import { chat, getChatRecord, getChatRecordList, deleteChat } from "../../api/student/AIChat/AIchat.js";
  
  const isSending = ref(false);
  const showHistoryDialog = ref(false);
  const selectedSessionId = ref(null);
  const userInput = ref('');
  const historyRecords = ref([]);
  const chatMessages = ref([]);
  
  onMounted(() => {
    getChat_RecordList(JSON.parse(localStorage.getItem("userInfo")).account);
  });
  
  const formatDate = (date) => {
    if (!date) return '';
    const d = new Date(date);
    return `${d.getFullYear()}-${(d.getMonth() + 1).toString().padStart(2, '0')}-${d.getDate().toString().padStart(2, '0')} ${d.getHours().toString().padStart(2, '0')}:${d.getMinutes().toString().padStart(2, '0')}`;
  };
  
  async function getChat_RecordList(data) {
    try {
      const response = await getChatRecordList(data);
      historyRecords.value = response;
    } catch (error) {
      console.error("获取聊天记录列表失败:", error);
    }
  }
  
  async function getChat_Record(data) {
    try {
      isSending.value = true;
      const response = await chat(data);
      chatMessages.value = response;
    } catch (error) {
      console.error("获取聊天记录失败:", error);
    } finally {
      isSending.value = false;
    }
  }
  
  const openHistoryDialog = (data) => {
    selectedSessionId.value = data[0].sessionId;
    chatMessages.value = data;
  };
  
  async function delete_Chat(account, sessionId) {
    try {
      await deleteChat(account, sessionId);
      getChat_RecordList(account);
      if (selectedSessionId.value === sessionId) {
        createNewConversation();
      }
    } catch (error) {
      console.error("删除聊天记录失败:", error);
    }
  }
  
  const handleDelete = (sessionId) => {
    const account = JSON.parse(localStorage.getItem("userInfo")).account;
    delete_Chat(account, sessionId);
  };
  
  const createNewConversation = () => {
    selectedSessionId.value = null;
    chatMessages.value = [];
    userInput.value = '';
  };
  
  const ChatData = ref({
    account: JSON.parse(localStorage.getItem("userInfo")).account,
    question: ''
  });
  
  const sendMessage = async () => {
    if (!userInput.value.trim()) return;
    
    const question = userInput.value.trim();
    userInput.value = '';
    
    // 添加到聊天记录
    chatMessages.value.push({
      question,
      answer: "思考中...",
      createTime: new Date().toISOString()
    });
    
    try {
      ChatData.value.question = question;
      await getChat_Record(ChatData.value);
    } catch (error) {
      // 更新最后一条消息为错误提示
      if (chatMessages.value.length > 0) {
        chatMessages.value[chatMessages.value.length - 1].answer = "抱歉，回答生成失败，请稍后再试。";
      }
    }
  };
  
  const clearInput = () => {
    userInput.value = '';
  };
  
  const closeAIChat = () => {
    // 可以添加关闭逻辑，如保存当前会话等
    console.log('AI聊天窗口关闭');
  };
  </script>
  
  <style scoped>
  .custom-scrollbar::-webkit-scrollbar {
    width: 6px;
    height: 6px;
  }
  
  .custom-scrollbar::-webkit-scrollbar-track {
    background: #f1f1f1;
    border-radius: 10px;
  }
  
  .custom-scrollbar::-webkit-scrollbar-thumb {
    background: #c1c1c1;
    border-radius: 10px;
  }
  
  .custom-scrollbar::-webkit-scrollbar-thumb:hover {
    background: #a8a8a8;
  }
  
  .ai-chat-dialog {
    border-radius: 12px;
    overflow: hidden;
  }
  
  .ai-chat-dialog :deep(.el-dialog__header) {
    display: none;
  }
  
  .ai-chat-dialog :deep(.el-dialog__body) {
    padding: 0;
  }
  
  @keyframes fadeIn {
    from { opacity: 0; transform: translateY(10px); }
    to { opacity: 1; transform: translateY(0); }
  }
  
  .animate-fade-in {
    animation: fadeIn 0.3s ease-out forwards;
  }
  
  .ai-chat-content {
    background-color: #f9fafb;
    border-radius: 8px;
    padding: 20px;
  }
  </style>